public class Solution {
    public int atoi(String str) {
        // Start typing your Java solution below
        // DO NOT write main() function

        int len = str.length();
        if (len < 1)
            return 0;
        int sign = 1;
        int index = 0;
        while (str.charAt(index) == ' ') {
            index++;
        }
        if (str.charAt(index) == '+') {
            index++;
        } else if (str.charAt(index) == '-') {
            sign = -1;
            index++;
        }
        long num = 0;
        for (; index < len; index++) {
            if (str.charAt(index) < '0' || str.charAt(index) > '9')
                break;
            num = num* 10 + (str.charAt(index) - '0');
            if (num > Integer.MAX_VALUE && sign == 1)
                break;
        }   
        if (num*sign > Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        if (num*sign < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        return (int)num*sign;
    }
}
